import Http from "http";

const lifecycle = process.env.npm_lifecycle_script || "";
const variable = (lifecycle.match(/NODE_ENV=(\w+)/) || [])[1] || "development"; // development|production|testing;

// serverMiddleware.js
export default (request, response, next) => {
    const path = request.url || "";

    if (path.indexOf("/drawer/") == 0) {
        const map = new Map([
            // ["development", "localhost"],
            ["development", "47.253.69.73"],
            ["testing", "47.253.69.73"],
            ["production", "alb-et4uiycfk0pxuoxqiq.us-east-1.alb.aliyuncs.com"],
        ]);

        const host = map.get(variable) || map.get("production");

        // 转换
        const options = {
            hostname: host,
            port: 8000,
            path: path.replace(/^\/drawer/, ""),
            method: request.method,
            headers: request.headers,
        };

        const proxy = Http.request(options, (drawer) => {
            response.writeHead(drawer.statusCode, drawer.headers);
            drawer.pipe(response);
        });

        request.pipe(proxy);
    } else {
        next();
    }
};
